<template>
  <XrCreateSingle :loading="loading"
                  :title="title"
                  @close="close"
                  @save="saveClick">
    <CreateSections title="基本信息">
      <el-form ref="crmFormRef"
               :model="fieldForm"
               :rules="fieldRules"
               :validate-on-rule-change="false"
               class="wk-form"
               label-position="top">
        <WkFormItems v-for="(children, index) in fieldList" :key="index"
                     :field-from="fieldForm" :field-list="children"
                     @change="formChange">
          <template v-slot:default="{ data }">
            <crm-relative-cell
                v-if="data && data.formType == 'customer'"
                :value="fieldForm[data.field]"
                :disabled="data.disabled"
                relative-type="customer"
                @value-change="otherChange($event, data)"
            />
            <crm-relative-cell
                v-if="data && (data.formType == 'business' || data.formType == 'contacts')"
                :value="fieldForm[data.field]"
                :disabled="data.disabled"
                :relation="data.relation"
                :relative-type="data.formType"
                @value-change="otherChange($event, data)"
            />
            <xh-product
                v-if="data && data.formType == 'product'"
                :value="fieldForm[data.field]"
                @value-change="otherChange($event, data)"
            />

          </template>
        </WkFormItems>
      </el-form>
    </CreateSections>
    <create-sections v-if="wkFlowList" title="审核信息">
      <template slot="header">
        <el-tooltip v-if="flowRemarks" :content="flowRemarks"
                    effect="dark"
                    placement="top">
          <i class="wk wk-help wk-help-tips" style="margin-left: 8px;"/>
        </el-tooltip>
      </template>
      <wk-approval-flow-apply
          :data="wkFlowList"
          style="padding: 15px;"
      />
    </create-sections>
    <template v-slot:footer>
      <el-button type="primary" plain
                 @click="debouncedSaveField(true)">保存草稿
      </el-button>
    </template>

  </XrCreateSingle>
</template>

<script setup>
import XrCreateSingle from '/src/szcomponent/XrCreateSingle'
import CreateSections from '/src/components/CreateSections'
import WkFormItems from '/src/components/NewCom/WkForm/WkFormItems'
import {useSzCustomFields} from "@/views/crm/hooks/create/useSzCustomFields.js";
import {ElMessage} from "element-plus"
import crmTypeModel from "@/views/crm/model/crmTypeModel.js";
import {filedGetFieldAPI} from "@/api/crm/common.js";
import {crmProductSaveAPI} from "@/api/crm/product.js";
import {crmContactsSaveAPI} from "@/api/crm/contacts.js";
import CrmRelativeCell from "components/CreateCom/CrmRelativeCell.vue";
import XhBusinessStatus from "components/CreateCom/XhBusinessStatus.vue";
import XhProduct from "components/CreateCom/XhProduct.vue";
import {objDeepCopy} from "utils";
import {useWkApprovalFlowApply} from "components/Examine/mixins/useWkApprovalFlowApply.js";
import moment from "moment";

defineOptions({
  // 新建编辑
  name: 'ContractCreate',
})

const props = defineProps({
  action: {
    type: Object,
    default: () => {
      return {
        type: 'save',
        id: '',
        data: {}
      }
    }
  }
})

const emits = defineEmits(['save-success', 'close'])

const loading = ref(false)
const ignoreFields = ref(['status'])
const baseFields = ref([])
const fieldList = ref([])
const fieldForm = ref({})
const fieldRules = ref({})
// 图片信息
const imageData = ref({
  mainFile: [],
  detailFile: []
})

const createOption = reactive({
  loading, ignoreFields, baseFields, fieldList, fieldForm, fieldRules, imageData
})

const hookCustomFields = useSzCustomFields(toRef(props, "action"), toRef(fieldRules))
const {
  approvalFlowOption,
  initWkFlowData, validateWkFlowData
} = useWkApprovalFlowApply()

const crmFormRef = ref()

const title = computed(() => {
  return props.action.type === 'update' ? '编辑合同' : '新建合同'
})

const wkFlowList = ref(null) // 有值有审批流
const flowRemarks = ref('')

// 确认名称
const sureBtnTitle = computed(() => {
  if (wkFlowList.value) {
    return '提交审核'
  }
  return '保存'
})


function created() {
  getField()
}

created()


/**
 * 获取数据
 */
function getField() {
  createOption.loading = true
  const params = {
    label: crmTypeModel.contract
  }

  if (props.action.type == 'update') {
    params.id = props.action.id
  }

  filedGetFieldAPI(params)
      .then(res => {
        const list = res.data.data || []

        const assistIds = hookCustomFields.getFormAssistIds(list)

        const baseFields = []
        const fieldList = []
        const fieldRules = {}
        const fieldForm = {}
        list.forEach(children => {
          const fields = []
          children.forEach(item => {
            const temp = hookCustomFields.getFormItemDefaultProperty(item)
            temp.show = !assistIds.includes(item.formAssistId)

            const canEdit = hookCustomFields.getItemIsCanEdit(item, props.action.type)
            // 是否能编辑权限
            if (temp.show && canEdit) {
              // 自动生成编号
              if (item.autoGeneNumber == 1) {
                temp.placeholder = '根据编号规则自动生成，支持手动输入'
                const copyItem = objDeepCopy(item)
                copyItem.isNull = 0
                fieldRules[temp.field] = hookCustomFields.getRules(copyItem)
              } else {
                fieldRules[temp.field] = hookCustomFields.getRules(item)
              }
            }

            // 是否可编辑
            temp.disabled = !canEdit

            // 禁止某些业务组件选择
            if (temp.formType == 'contacts' ||
                temp.formType == 'customer' ||
                temp.formType == 'business'
            ) {
              if (props.action.type == 'relative') {
                const relativeDisInfos = {
                  contacts: {customer: true},
                  customer: {customer: true},
                  business: {customer: true, business: true}
                }

                // 在哪个类型下添加
                const relativeTypeDisInfos = relativeDisInfos[props.action.crmType]
                if (relativeTypeDisInfos) {
                  // 包含的字段值
                  temp.disabled = relativeTypeDisInfos[item.formType] || false
                }
              } else if (props.action.type != 'update') {
                temp.disabled = item.formType === 'business' || item.formType === 'contacts'
              }
            }

            // 处理关联
            if ((props.action.type == 'relative' || props.action.type == 'update') && (item.formType == 'business' || item.formType == 'contacts' || item.formType == 'contract'
            )) {
              const customerObj = hookCustomFields.getItemRelatveInfo(list, 'customer')
              if (customerObj) {
                const customerItem = objDeepCopy(customerObj)
                if (item.formType == 'business' || item.formType == 'contacts') {
                  customerItem['moduleType'] = 'customer'
                  temp['relation'] = customerItem
                } else if (item.formType == 'contract') {
                  customerItem['moduleType'] = 'customer'
                  customerItem['params'] = {checkStatus: [1, 10]}
                  temp['relation'] = customerItem
                }
              }
            }
            // 特殊字段允许多选
            hookCustomFields.getItemRadio(item, temp)

            // 获取默认值
            // 非编辑情况下 填充默认值
            if (temp.show) {
              if (props.action.type != 'update' && item.fieldName === 'orderDate') {
                fieldForm[temp.field] = moment().format('YYYY-MM-DD')
              } else {
                fieldForm[temp.field] = hookCustomFields.getItemValue(item, props.action.data, props.action.type)
              }
            }
            fields.push(temp)
            baseFields.push(item)
          })
          fieldList.push(fields)
        })


        // 填充商机关联的产品信息
        if (props.action.type == 'relative') {
          const businessData = props.action.data.business
          if (businessData) {
            hookCustomFields.getBusinessProduct(businessData.businessId).then(resData => {
              const businessData = resData || {}
              fieldForm.product = {
                product: businessData.list,
                totalPrice: businessData.money,
                discountRate: businessData.discountRate
              }
              fieldForm.money = businessData.money || ''
            }).catch(() => {
            })
          }
        }

        createOption.baseFields = baseFields
        createOption.fieldList = fieldList
        createOption.fieldForm = fieldForm
        createOption.fieldRules = fieldRules

        // 审核信息
        initWkFlowData({
          params: {label: 1},
          fieldForm: fieldForm
        }, (res) => {
          wkFlowList.value = res.list
          flowRemarks.value = res.resData ? res.resData.remarks : ''
        })
        createOption.loading = false
      })
      .catch(() => {
        createOption.loading = false
      })
}

/**
 * 获取数据
 */
function getField2() {
  createOption.loading = true
  const params = {
    label: crmTypeModel.contract
  }

  if (props.action.type == 'update') {
    params.id = props.action.id
  }

  filedGetFieldAPI(params).then(res => {
    const list = res.data.data || []

    const assistIds = hookCustomFields.getFormAssistIds(list)

    const baseFields = []
    const fieldList = []
    const fieldRules = {}
    const fieldForm = {}
    list.forEach(children => {
      const fields = []
      children.forEach(item => {
        const temp = hookCustomFields.getFormItemDefaultProperty(item)
        temp.show = !assistIds.includes(item.formAssistId)

        if (createOption.ignoreFields.includes(temp.field)) {
          // 防止影响普通单选的验证方式
          delete temp.optionsData
          delete item.optionsData
        }

        const canEdit = hookCustomFields.getItemIsCanEdit(item, props.action.type)
        // 是否能编辑权限
        if (temp.show && canEdit) {
          fieldRules[temp.field] = hookCustomFields.getRules(item)
        }

        // 是否可编辑
        temp.disabled = !canEdit

        // 特殊字段允许多选
        hookCustomFields.getItemRadio(item, temp)

        // 获取默认值
        if (temp.show) {
          if (createOption.ignoreFields.includes(temp.field)) {
            fieldForm[temp.field] = props.action.type === 'update' ? temp.value : temp.defaultValue
          } else {
            fieldForm[temp.field] = hookCustomFields.getItemValue(item, props.action.data, props.action.type)
          }
        }
        fields.push(temp)
        baseFields.push(item)
      })
      fieldList.push(fields)
    })

    createOption.baseFields = baseFields
    createOption.fieldList = fieldList
    createOption.fieldForm = fieldForm
    createOption.fieldRules = fieldRules

    createOption.loading = false
  }).catch(() => {
    createOption.loading = false
  })
}

/**
 * 保存
 */
function saveClick() {
  createOption.loading = true
  // const crmForm = .$refs.crmForm
  crmFormRef.value.validate(valid => {
    if (valid) {
      const params = hookCustomFields.getSubmiteParams([].concat.apply([], createOption.fieldList), createOption.fieldForm)
      // 图片信息
      params.entity.mainFileIds = createOption.imageData.mainFile ? createOption.imageData.mainFile.map(item => item.fileId).join(',') : ''
      params.entity.detailFileIds = createOption.imageData.detailFile ? createOption.imageData.detailFile.map(item => item.fileId).join(',') : ''
      submitParams(params)
    } else {
      createOption.loading = false
      // 提示第一个error
      hookCustomFields.getFormErrorMessage(crmFormRef.value)
      // return false
    }
  })
}

/**
 * 提交上传
 */
function submitParams(params) {
  if (props.action.type == 'update') {
    params.entity.productId = props.action.id
    params.entity.batchId = props.action.batchId
  }
  // 相关添加时候的多余提交信息
  if (props.action.relativeData &&
      Object.keys(props.action.relativeData).length) {
    params = {...params, ...props.action.relativeData}
  }
  crmContactsSaveAPI(params).then(res => {
    createOption.loading = false

    ElMessage.success({message: props.action.type == 'update' ? '编辑成功' : '添加成功'})
    // .$message.success(.action.type == 'update' ? '编辑成功' : '添加成功')

    close()

    // 保存成功
    emits('save-success', {type: 'product'})
  }).catch((e) => {
    console.log("e", e)
    createOption.loading = false
  })
}

/**
 * 验证唯一
 */
function UniquePromise({field, value}) {
  return hookCustomFields.getUniquePromise(field, value, props.action)
}

/**
 * change
 */
function formChange(field, index, value, valueList) {
  console.log("formChange", field, index, value, valueList)
  if ([
        'select',
        'checkbox'
      ].includes(field.formType) &&
      field.remark === 'options_type' &&
      field.optionsData) {
    const {
      fieldForm,
      fieldRules
    } = hookCustomFields.getFormContentByOptionsChange(createOption.fieldList, createOption.fieldForm)
    createOption.fieldForm = fieldForm
    createOption.fieldRules = fieldRules
  } else {
    fieldForm.value[field.field] = value
    console.log(fieldForm)
  }
}

/**
 * 地址change
 */
function otherChange(data, field) {
  // .$set(.fieldForm, field.field, data.value)
  createOption.fieldForm[field.field] = data.value
  // .$refs.crmForm.validateField(field.field)
  crmFormRef.value.validateField(field.field)
}


/**
 * 关闭
 */
function close() {
  emits('close')
}

</script>


<style lang="scss" scoped>
</style>
